package Dao.daoImpl;

import Dao.empDao;
import Model.Emp;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import tools.initLogRecord;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;

public class EmpDaoImpl {
    private static InputStream in;
    private static SqlSessionFactory factory;
    private static SqlSession sqlSession;
    private static empDao empDao;

    public static void init() throws IOException {
        //1.读取加载核心配置文件
        in = Resources.getResourceAsStream("config/mybatis-config.xml");
        //2.构造会话工厂
        factory = new SqlSessionFactoryBuilder().build(in);
        //3.创建对象会话
        sqlSession = factory.openSession();
        empDao = sqlSession.getMapper(empDao.class);

    }


    @Test
    public void addEmpDao(Emp obj) throws SQLException, IOException {
        init();
        empDao.addEmpDao(obj);
        sqlSession.commit();
        System.out.println("yes");

    }


    @Test
    public List<Emp> showEmpDao() throws IOException {
        init();
//        List<Object> showEmpDao = sqlSession.selectList("showEmpDao");
//        for (Object o : showEmpDao) {
//            System.out.println(o);
        List<Emp> emps = empDao.showEmpDao();
        for (Emp o : emps) {
            System.out.println("o = " + o);
        }
        return emps;
    }


    @Test
    public void delEmpDao(int empId) throws SQLException, IOException {
        init();
//        int i = sqlSession.update("delEmpDao");
        empDao.delEmpDao(empId);
        sqlSession.commit();
        System.out.println("yes");
    }

    @Test
    public boolean updateEmpDao(Emp obj) throws SQLException, IOException {

        //日志管理
        initLogRecord.initLog();
        init();
        empDao.update(obj);
        sqlSession.commit();
        return false;
    }


    @Test
    public Object findOneDataDao(int empId1) throws IOException {
        init();
        Object findOneDataDao = empDao.findOneDataDao(empId1);
        return findOneDataDao;
    }
}
